(function ($) {
    $.fn.yqTextRichEdit = function (opts, param) {
        if (typeof opts == 'string') {
            return $.fn.yqTextRichEdit.methods[opts](this, param);
        }

        return this.each(function () {
            var $this = $(this);
            var opt;
            if ($this.data("yqtype") == "yqTextRichEdit") {
                var $uniqueID = $this.attr("ID");
                var opts_ = $.extend({}, options($this));
                destroy($this);
                $this = $("#" + $uniqueID);
                opt = $.extend(opts_, opts);
            }
            else {
                opt = $.extend({}, $.fn.yqTextRichEdit.defaults, opts);
                var $uniqueID = $this.attr("ID");
                if ($uniqueID === undefined || $uniqueID === null || $uniqueID == "") {
                    $uniqueID = $.getUniqueID();
                    $this.attr("ID", $uniqueID);
                }
            }

            if (opt.width === undefined && $this.width() > 0) {
                opt.width = $this.width();
            }
            else if (typeof opt.width != "undefined") {
                $this.width(opt.width);
            }

            opt.onload = true;

            //变量信息
            $this.data("textrichedit_opt", opt);
            $this.data("yqtype", "yqTextRichEdit");

            init_text($this);
        });
    };

    $.fn.yqTextRichEdit.defaults = {
        editType: 1,   //1-html,2-markdown
        storageType: 3,//1-数据库存储，2-外部存储
        storageName: null,
        accept: "image/*",
        chunk: false,       //分片上传
        directup: false,   //直接上传（选择文件后立即上传）
        data: { files: [], html: "" },
        isEdit: true,   //可编辑
        editModeW: 700, //模态编辑器宽度 格式为 800（数字）
        editModeH: 400, //模态编辑器高度 格式为 600（数字）
        beforeChange: function (value, callback) {
            callback(true, value);
        }
    };

    $.fn.yqTextRichEdit.methods = {
        options: function (jq) {
            return options($(jq[0]));
        },
        destroy: function (jq) {
            destroy($(jq[0]));
        },
        resize: function (jq, width) {
            resize($(jq[0]), width);
        },
        clear: function (jq, data) {
            setValue($(jq[0]), null);
        },
        setData: function (jq, data) {
            setData($(jq[0]), data);
        },
        getData: function (jq) {
            return getData($(jq[0]));
        },
        isEdit: function (jq, tf) {
            isEdit($(jq[0]), tf);
        },
    };

    function options($object) {
        return $object.data("textrichedit_opt");
    }

    function destroy($object) {
        var opt = options($object);
        var $new_obj = $($object.prop("outerHTML"));
        $new_obj.show();
        var id = $object.attr("id");
        $new_obj.removeAttr("id");
        $new_obj.removeClass("textbox-f");
        $object.before($new_obj);

        $object.textbox("destroy");

        $new_obj.attr("id", id);

        $object.removeData("textrichedit_opt");
        $object.removeData("yqtype");
    }

    function resize($object, width) {
        $object.textbox("resize", width);
    }

    function init_text($object) {
        var opt = options($object);
        var $uniqueID = $object.attr('id');

        var text_opt = {
            editable: false,
            iconAlign: 'right',
            icons: [{
                iconCls: 'yqwin-combo-btn-icon fa fa-pencil',
                handler: function (e) {
                    var pp = $object.textbox("textbox");;
                    prevent_e = $.getPreventDefault(pp[0]);
                    prevent_e.id = $object.attr("id");
                    prevent_e.options = opt;

                    var mdiinfo = $.yqGetWindParams();

                    var run_opt = {
                        mdiinfo: mdiinfo,
                        prevent_e: prevent_e,
                        width: opt.editModeW,
                        height: opt.editModeH,

                        storageType: opt.storageType,//1-数据库存储，2-外部存储
                        storageName: opt.storageName,
                        accept: opt.accept,
                        chunk: opt.chunk,       //分片上传
                        directup: opt.directup,   //直接上传（选择文件后立即上传）
                        data: opt.data,

                        isEdit: opt.isEdit,   //可编辑
                        lang: opt.lang, //语言

                        callback: function (data) {
                            //嵌入到datagrid中，兼容处理（需要重新创建对象）
                            if (typeof opt.p_target != "undefined") {
                                var ed = $.yqTextEditor(opt.p_target, opt.p_field);
                                if (!(ed === null)) {
                                    $(ed.target).yqTextRichEdit('setData', data);
                                }
                            }
                            else {
                                setData($object, data);
                            }
                        }
                    };

                    if (opt.editType == 1) {
                        if (window.top == window.self) {
                            $.yqHtmlPopEdit(run_opt);
                        }
                        else {
                            window.top.$.yqHtmlPopEdit(run_opt);
                        }
                    }
                    else if (opt.editType == 2) {
                        run_opt.type = "md";
                        run_opt.types = ["md"];
                        run_opt.callbackType = 2;   //返回value，2返回data
                        if (window.top == window.self) {
                            $.yqCodePopEdit(run_opt);
                        }
                        else {
                            window.top.$.yqCodePopEdit(run_opt);
                        }
                    }
                }
            }, {
                iconCls: 'yqwin-combo-btn-icon fa fa-times',
                //disabled:true,
                handler: function (e) {
                    setData($object, null);
                }
            }]
        };

        $object.textbox(text_opt);
        setData($object, opt.data);
        isEdit($object, opt.isEdit);
    }

    function setData($object, data) {
        var opt = options($object);
        if (typeof data == "string") {
            data = JSON.parse(data);
        }
        else if (typeof data != "object") {
            data = null;
        }
        if (data === null) {
            if(opt.editType==1){
                data = { files: [], html: "" };
            }else if(opt.editType==2){
                data = { files: [], code: "" };
            }
        }
        opt.data = data;
        if(opt.editType==1){
            $object.textbox("setValue", data.html);
        }else if(opt.editType==2){
            $object.textbox("setValue", data.code);
        }
       
    }

    function getData($object) {
        var opt = options($object);
        return opt.data;
    }

    function isEdit($object, tf) {
        var opt = options($object);
        var icon0 = $object.textbox("getIcon", 0);
        var icon1 = $object.textbox("getIcon", 1);
        opt.isEdit = tf;
        if (opt.isEdit) {
            icon0.removeClass('icon-more');
            icon0.addClass('icon-edit');
            icon1.show();
            //icon1.removeClass('textbox-icon-disabled');
        } else {
            icon0.removeClass('icon-edit');
            icon0.addClass('icon-more');
            //icon1.addClass('textbox-icon-disabled');
            icon1.hide();
        }
    }
})(jQuery);
